package org.dreamwork.cai.spring;

import org.dreamwork.cai.core.IHeartbeatManager;
import org.dreamwork.cai.core.impl.HeartbeatManager;
import org.dreamwork.cai.io.IRouteBroadcaster;
import org.dreamwork.cai.proxy.IServiceResolver;
import org.dreamwork.cai.srf.ServiceRouteTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SpringHeartbeatManagerBridge implements IHeartbeatManager {
    private final Logger logger = LoggerFactory.getLogger (SpringHeartbeatManagerBridge.class);

    private HeartbeatManager heartbeat;

    private int scanInterval;

    private int sendInterval;

    private int timeout;

    private final IServiceResolver resolver;

    public SpringHeartbeatManagerBridge (@Autowired IServiceResolver resolver) {
        this.resolver = resolver;
    }

    public void setScanInterval (int scanInterval) {
        this.scanInterval = scanInterval;
    }

    public void setSendInterval (int sendInterval) {
        this.sendInterval = sendInterval;
    }

    public void setTimeout (int timeout) {
        this.timeout = timeout;
    }

    @Override
    public void start () {
        this.heartbeat = new HeartbeatManager ();
        heartbeat.setResolver (resolver);
        heartbeat.setTable (resolver.get (ServiceRouteTable.class));
        heartbeat.setBroadcaster (resolver.get (IRouteBroadcaster.class));

        heartbeat.setScanInterval (scanInterval);
        heartbeat.setSendInterval (sendInterval);
        heartbeat.setTimeout (timeout);

        if (logger.isTraceEnabled ()) {
            logger.trace ("scan interval = {}", scanInterval);
            logger.trace ("send interval = {}", sendInterval);
            logger.trace ("timeout = {}", timeout);
        }

        heartbeat.start ();
    }

    @Override
    public void shutdown () {
        heartbeat.shutdown ();
    }

    @Override
    public void touch (String host, int port) {
        heartbeat.touch (host, port);
    }

    @Override
    public void remove (String host) {
        heartbeat.remove (host);
    }
}